package main

import (
	//"encoding/json"
	"encoding/json"
	"log"
	"net/http"
	"strconv"

	"gitee.com/czy233/go-ceph/rados"
)

type Object struct {
	Obj_id  string `json:"obj"`
	Content []byte `json:"content"`
}

func (s *Ceph) CheckFromCeph(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	oid := r.FormValue("oid")
	offset, err := strconv.ParseUint(r.FormValue("off"), 10, 64)
	if err != nil {
		log.Println("cluster", Cluster, ":", "parse offset to uint error")
		return
	}

	var data []byte
	data = make([]byte, 4096*1024)
	dlen, err := s.ioctx.Read(oid, data, 0)
	if err != nil {
		log.Println("cluster", Cluster, ":", "错误 被抽查读取 obj:", err)
		return
	}
	if dlen != 4096*1024 {
		log.Println("cluster", Cluster, ":", "错误 数据长度不足 被抽查读取 obj:", err)
		return
	}

	var m MerkleTree
	m.InitConfig([]int{1, 32, 32})
	err = m.GenerateTree(data)
	if err != nil {
		log.Println("cluster", Cluster, ":", "generate mktree error", "oid", oid, "offset", offset)
		return
	}
	proof, err := m.GenerateMerkleProof(int(offset))
	//fmt.Println(proof)
	if err != nil {
		log.Println("cluster", Cluster, ":", "generate mktree proof error", "oid", oid, "offset", offset)
		return
	}
	proof_byte, err := json.Marshal(proof)

	send_len, _ := w.Write(proof_byte)
	log.Println("cluster", Cluster, ":", "generate obj: ", oid, ", offset:", offset, "sendlength: ", send_len)

}

func InitsServer() {
	conn, err := rados.NewConn()
	if err != nil {
		log.Println("cluster", Cluster, ":", "error when invoke a new connection:", err)
		return
	}
	defer conn.Shutdown()

	err = conn.ReadConfigFile("/etc/ceph/ceph.conf")
	if err != nil {
		log.Println("cluster", Cluster, ":", "error when read default config file:", err)
		return
	}

	err = conn.Connect()
	if err != nil {
		log.Println("cluster", Cluster, ":", "error when connect:", err)
		return
	}

	log.Println("cluster", Cluster, ":", "connect ceph cluster ok!")

	ioctx, err := conn.OpenIOContext("testbench")
	if err != nil {
		log.Println("cluster", Cluster, ":", "error when open IO context:", err)
		return
	}
	ceph := &Ceph{
		ioctx: ioctx,
	}

	http.HandleFunc("/check", ceph.CheckFromCeph)

	http.ListenAndServe(":8080", nil)
	log.Println("cluster", Cluster, ":", "service start ...")
}
